<?php

namespace app\controllers;


use Yii;
use yii\web\Controller;
use zonday\weixin\WeixinAuthorize;
use zonday\weixin\api;

/**
 * Class FooController
 * @method readAccessToken()
 */
class FooController extends Controller
{
    public function behaviors()
    {
        return [
            'weixinAuthorize' => [
                'class' => WeixinAuthorize::className(),
                'autoLogin' => false,
                'scopeMap' => [
                    'unsubscribe' => WeixinAuthorize::SCOPE_SNSAPI_USERINFO,
                ]
            ],
        ];
    }

    public function actionIndex()
    {
        $accessToken = $this->readAccessToken();
        $userApi = new api\User();
        $userInfo = $userApi->info($accessToken['openid']);
        if ($userInfo['subscribe'] == 0) {
            return $this->redirect(['unsubscribe']);
        }
        return $this->render('index', [
            'userInfo' => $userInfo,
        ]);
    }

    public function actionUnsubscribe()
    {
        $accessToken = $this->readAccessToken();
        $userInfo = Yii::$app->weixin->snsUserInfo($accessToken['openid'], $accessToken['access_token']);
        return $this->render('index', [
            'userInfo' => $userInfo,
        ]);
    }
}